import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_yishop/constants/Constants.dart';
import 'package:flutter_yishop/services/SearchServices.dart';
import 'package:flutter_yishop/utils/screen/ScreenAdapter.dart';
import 'package:flutter_yishop/utils/toast_util.dart';

class Search extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _Search();
  }
}

class _Search extends State<Search> {
  String _keyWords;
  TextEditingController _searchController = TextEditingController();
  List _historyListData = [];
  List _hotSearchListData = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    setState(() {
      _getHistoryData();
    });
  }

  _getHistoryData() async {
    var _historyListData = SearchServices.getHistoryList();
    var _hotSearchListData = SearchServices.getHotSearchList();
    setState(() {
      this._historyListData = _historyListData;
      this._hotSearchListData = _hotSearchListData;
    });
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    ScreenAdapter.init(context);
    setState(() {
      _getHistoryData();
    });

    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        title: Container(
          height: ScreenAdapter.height(68),
          padding: EdgeInsets.fromLTRB(
              ScreenAdapter.width(30), 0, ScreenAdapter.width(30), 0),
          child: Row(
            children: [
              Icon(
                Icons.search,
                color: Colors.black38,
                size: 20,
              ),
              SizedBox(
                width: ScreenAdapter.width(15),
              ),
              Expanded(
                child: TextField(
                  controller: _searchController,
                  decoration: InputDecoration(
                    focusedBorder: OutlineInputBorder(
                        borderSide:
                            BorderSide(width: 0, color: Colors.transparent)),
                    disabledBorder: OutlineInputBorder(
                        borderSide:
                            BorderSide(width: 0, color: Colors.transparent)),
                    enabledBorder: OutlineInputBorder(
                        borderSide:
                            BorderSide(width: 0, color: Colors.transparent)),
                    border: OutlineInputBorder(
                        borderSide:
                            BorderSide(width: 0, color: Colors.transparent)),
                    contentPadding: EdgeInsets.symmetric(vertical: 0),
                  ),
                  onChanged: (value) {
                    this._keyWords = value;
                  },
                ),
              ),
            ],
          ),
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(30),
              color: Color.fromRGBO(233, 233, 233, 0.8)),
        ),
        actions: [
          Container(
            margin: EdgeInsets.only(right: ScreenAdapter.width(20)),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                GestureDetector(
                  child: Text("搜索"),
                  onTap: () {
                    if (_searchController.text == null ||
                        _searchController.text.isEmpty ||
                        this._keyWords == null ||
                        this._keyWords.isEmpty) {
                      print(("请输入关键词"));
                      ToastUtil.showToasts("请输入关键词");
                    } else {
                      SearchServices.setHistoryData(this._keyWords);
                      Navigator.pushNamed(context, Constants.PRODUCT,
                          arguments: {
                            'keyWords': this._keyWords,
                            "title": this._keyWords
                          });
                    }
                  },
                ),
              ],
            ),
          ),
        ],
      ),
      body: ListView(
        children: [
          _getHostSearchListWidget(),
          _getHistoryListWidget(),
        ],
      ),
    );
  }

  ///获取热搜
  Widget _getHostSearchListWidget() {
    if (SearchServices.getHotSearchList().length > 0) {
      return Column(
        children: [
          Container(
            alignment: Alignment.centerLeft,
            margin: EdgeInsets.fromLTRB(ScreenAdapter.width(20),
                ScreenAdapter.height(20), ScreenAdapter.width(20), 0),
            child: Text(
              "热搜",
              style: TextStyle(
                fontSize: ScreenAdapter.size(40),
                color: Colors.black,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          Divider(),
          Row(
            children: [
              Wrap(
                children: SearchServices.getHotSearchList().map((value) {
                  return  GestureDetector(
                    child: Container(
                      padding: EdgeInsets.all(10),
                      margin: EdgeInsets.all(10),
                      child: Text("$value"),
                      decoration: BoxDecoration(
                          color: Color.fromRGBO(233, 233, 233, 0.8),
                          borderRadius: BorderRadius.circular(10.0)),
                    ),
                    onTap: () {
                      SearchServices.setHistoryData(value);
                      Navigator.pushNamed(context, Constants.PRODUCT,
                          arguments: {'keyWords': value, "title": value});
                    },
                  );
                }).toList(),
              ),
            ],
          ),
        ],
      );
    } else {
      return Text("");
    }
  }

  ///获取历史记录
  Widget _getHistoryListWidget() {
    if (this._historyListData.length > 0) {
      return Column(
        children: [
          Container(
            alignment: Alignment.centerLeft,
            margin: EdgeInsets.fromLTRB(ScreenAdapter.width(20),
                ScreenAdapter.height(20), ScreenAdapter.width(20), 0),
            child: Text(
              "历史记录",
              style: TextStyle(
                fontSize: ScreenAdapter.size(40),
                color: Colors.black,
                fontWeight: FontWeight.bold
              ),
            ),
          ),
          Column(
            children: this._historyListData.map((value) {
              return Column(
                children: <Widget>[
                  ListTile(
                    title: Text("${value}"),
                    onLongPress: () {
                      this._showAlertDialog("${value}");
                    },
                    onTap: () {
                      SearchServices.setHistoryData(value);
                      Navigator.pushNamed(context, Constants.PRODUCT,
                          arguments: {'keyWords': value, "title": value});
                    },
                  ),
                  Divider()
                ],
              );
            }).toList(),
          ),
          SizedBox(
            height: ScreenAdapter.height(50),
          ),
          Container(
            margin: EdgeInsets.fromLTRB(
                ScreenAdapter.width(30), 0, ScreenAdapter.width(30), 0),
            child: OutlineButton(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(Icons.delete),
                  SizedBox(
                    width: ScreenAdapter.width(20),
                  ),
                  Text("清空历史记录"),
                ],
              ),
              onPressed: () {
                setState(() {
                  SearchServices.clearAllHistroy();
                  _getHistoryData();
                });
              },
            ),
          ),
        ],
      );
    } else {
      return Text("");
    }
  }

  _showAlertDialog(keywords) async {
    var result = await showDialog(
        context: context,
        barrierDismissible: false, //表示点击灰色背景是否消失弹框
        builder: (context) {
          return AlertDialog(
            title: Text("提示信息"),
            content: Text("您确定要删除吗？"),
            actions: [
              FlatButton(
                  onPressed: () {
                    Navigator.pop(context, 'Cancel');
                  },
                  child: Text("取消")),
              FlatButton(
                  onPressed: () {
                    SearchServices.clearHistroyList(keywords);
                    this._getHistoryData();
                    Navigator.pop(context, 'OK');
                  },
                  child: Text("确定")),
            ],
          );
        });
  }
}
